import { Footer, AvatarDropdown } from '@/components';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig, getCurrentUser, handel401 } from './requestErrorConfig';
import React from 'react';
import { App, Flex } from 'antd';
const loginPath = '/user/login';
import Avator from '@/assets/images/login/avator_white.png';
import NoAccessPage from './pages/403';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import ErrorBoundary from './ErrorBoundary.jsx';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const token = getCurrentUser();
      if (token) {
        return {
          ...token,
          menuList: [],
        };
      } else {
        handel401();
      }
    } catch (error) {
      handel401();
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath && location.pathname !== '/user/forget-password') {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    actionsRender: () => [],
    avatarProps: {
      src: initialState?.currentUser?.avatar || Avator,
      render: (_, avatarChildren) => {
        return (
          <AvatarDropdown>
            <Flex align="center" justify="center" gap={5}>
              {avatarChildren}
              <span className="main_header_username">{initialState?.currentUser?.username}</span>
            </Flex>
          </AvatarDropdown>
        );
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.username || '',
      fontColor: 'rgba(0,0,0,0.05)',
      fontSize: 20,
      rotate: -22,
      gapY: 100,
      gapX: 100,
    },
    headerRender(props, defaultDom: any) {
      return (
        <App component={false}>
          <div className="main_header_box">
            <div className="main_header">{defaultDom}</div>
          </div>
        </App>
      );
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      if (
        !initialState?.currentUser &&
        location.pathname !== loginPath &&
        location.pathname !== '/user/forget-password'
      ) {
        history.push(loginPath);
      }
    },
    contentStyle: {
      minHeight: 'calc(100vh - 175px)',
      padding: '0px',
    },
    bgLayoutImgList: [],
    links: [],
    // 自定义 403 页面
    unAccessible: <NoAccessPage />,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <ErrorBoundary>
          <App component={false}>
            {children}
            <ToastContainer />
          </App>
        </ErrorBoundary>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};

// const initRoute = (routes: any[]) => {
//   for (let index = 0; index < routes.length; index++) {
//     const element = routes[index];
//     if (element.routes?.length > 0) {
//       noComponentPaths.push(element.path);
//     }
//     if (element.path !== '/' && !element.path.includes('/user') && element.path !== '*') {
//       element.access = 'routeAccess';
//     }
//     initRoute(element.children || []);
//     initRoute(element.routes || []);
//   }
// };

export const patchClientRoutes = () => {};

export function onRouteChange() {}
